import Koa from 'koa';
import config from "./config";
import log4js from 'log4js';
import errorHandler from './middlewares/errorHandler';
//import router from 'koa-simple-router';
import render from 'koa-swig';
import co from 'co';
import serve from 'koa-static';
const { asClass, asValue, createContainer , Lifetime} = require('awilix');
const { loadControllers,scopePerRequest } = require('awilix-koa');

const app = new Koa();

// log
log4js.configure({
  appenders: { err: { type: 'file', filename: 'logs/err.log' } },
  categories: { default: { appenders: ['err'], level: 'error' } }
});
const logger = log4js.getLogger('err');

// error
errorHandler.error(app,logger);

// swig
app.context.render = co.wrap(render({
  root: config.viewsPath,
  autoescape: true,
  cache: 'memory', // disable, set to false
  ext: 'html',
  varControls:["[[","]]"],//修改变量控制符为[[]],而不是原来的{{}}，避免与vue冲突
  writeBody: false
}));

// awilix-------
//创建IOC的容器
const container = createContainer();

//装载所有的models 并将services代码注入到controllers
container.loadModules(['services/*.js'], {
    formatName: 'camelCase',
    cwd: __dirname,//注意此处添加路径，不然找不到service
    resolverOptions: {
      lifetime: Lifetime.SCOPED
    }
  })
  

//每一次的请求都是一个 new model
app.use(scopePerRequest(container));

//注册所有的路由
app.use(loadControllers('controllers/*.js', { cwd: __dirname }));
// awilix-------end


// static
app.use(serve(config.staticPath));



app.listen(config.port, () => {
  console.log(`myweb listening on ${config.port}`);
});